<template>
  <div class="mod-config">
    <el-form :inline="true" :model="queryForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        &emsp;<el-date-picker
        type="daterange"
        v-model="queryForm.date"
        value-format="yyyy-MM-dd"
        range-separator="~"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        clearable>
      </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
      </el-form-item>
      <el-form-item style="float:right">
        <el-button type="primary" @click.native="exportVisible()">导出<i class="el-icon-download el-icon--right"></i>
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      :header-cell-style="{background:'#F5F7FA',color:'#606266'}"
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        prop="roomTypeName"
        header-align="center"
        align="center"
        label="房类名称">
      </el-table-column>
      <el-table-column
        prop="mebName"
        header-align="center"
        align="center"
        label="会员姓名">
      </el-table-column>
      <el-table-column
        prop="superiorType"
        :formatter="typeFormatter"
        header-align="center"
        align="center"
        label="上级类型">
      </el-table-column>
      <el-table-column
        prop="superiorName"
        header-align="center"
        align="center"
        label="上级名称">
      </el-table-column>
      <el-table-column
        prop="price"
        header-align="center"
        align="center"
        label="价格">
      </el-table-column>
      <el-table-column
        prop="date"
        header-align="center"
        align="center"
        label="统计日期">
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <el-dialog
      title="导出设置"
      width="50%"
      :visible.sync="exportVis">
      <el-form :model="exportForm"
               label-width="80px"
               :rules="dataRule"
               ref="exportForm"
               @keyup.enter.native="exportSubmit()">
        <el-row :gutter="this.gutter">
          <el-col :span="this.span">
            <el-form-item label="单位奖励" prop="unit">
              <el-input v-model="exportForm.unit" type="number" placeholder="单位奖励">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="this.span">
            <el-form-item label="时间段" prop="unitPeriod">
              <el-date-picker
                v-model="exportForm.unitPeriod"
                type="daterange"
                value-format="yyyy-MM-dd"
                align="right"
                unlink-panels
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="this.gutter">
          <el-col :span="this.span">
            <el-form-item label="员工奖励" prop="staff">
              <el-input v-model="exportForm.staff" type="number" placeholder="员工奖励">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="this.span">
            <el-form-item label="时间段" prop="staffPeriod">
              <el-date-picker
                v-model="exportForm.staffPeriod"
                type="daterange"
                value-format="yyyy-MM-dd"
                align="right"
                unlink-panels
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="this.gutter">
          <el-col :span="this.span">
            <el-form-item label="前台奖励" prop="frontDesk">
              <el-input v-model="exportForm.frontDesk" type="number" placeholder="前台奖励">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="this.span">
            <el-form-item label="时间段" prop="frontPeriod">
              <el-date-picker
                v-model="exportForm.frontPeriod"
                type="daterange"
                align="right"
                value-format="yyyy-MM-dd"
                unlink-panels
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="this.gutter">
          <el-col :span="this.span">
            <el-form-item label="餐吧奖励" prop="res">
              <el-input v-model="exportForm.res" type="number" placeholder="餐吧奖励">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="this.span">
            <el-form-item label="时间段" prop="resPeriod">
              <el-date-picker
                v-model="exportForm.resPeriod"
                type="daterange"
                align="right"
                unlink-panels
                value-format="yyyy-MM-dd"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exportVis = false">取消</el-button>
        <el-button type="primary" @click="exportSubmit()" :loading="this.isLoading">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import AddOrUpdate from './record-add-or-update'

  export default {
    data () {
      return {
        queryForm: {
          date: [],
          startDate: '',
          endDate: ''
        },
        exportForm: {
          unit: 0,
          staff: 0,
          frontDesk: 0,
          res: 0,
          unitPeriod: [],
          staffPeriod: [],
          resPeriod: [],
          frontPeriod: []
        },
        dataRule: {
          unit: [
            {required: true, message: '单位奖励不能为空', trigger: 'blur'}
          ],
          unitPeriod: [
            {required: true, message: '时间段不能为空', trigger: 'blur'}
          ],
          staff: [
            {required: true, message: '员工奖励不能为空', trigger: 'blur'}
          ],
          staffPeriod: [
            {required: true, message: '时间段不能为空', trigger: 'blur'}
          ],
          frontDesk: [
            {required: true, message: '前台奖励不能为空', trigger: 'blur'}
          ],
          frontPeriod: [
            {required: true, message: '时间段不能为空', trigger: 'blur'}
          ],
          res: [
            {required: true, message: '餐厅吧台奖励不能为空', trigger: 'blur'}
          ],
          resPeriod: [
            {required: true, message: '时间段不能为空', trigger: 'blur'}
          ]
        },
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        isLoading: false,
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        rewardVisible: false,
        exportVis: false,
        gutter: 20,
        span: 10
      }
    },
    components: {
      AddOrUpdate
    },
    activated () {
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      getDataList () {
        this.dateHandle()
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/tra/record/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'startDate': this.queryForm.startDate,
            'endDate': this.queryForm.endDate
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      dateHandle () {
        this.queryForm.startDate = ''
        this.queryForm.endDate = ''
        if (this.queryForm.date !== null) {
          this.queryForm.startDate = this.queryForm.date[0]
          this.queryForm.endDate = this.queryForm.date[1]
        }
      },
      // 删除
      deleteHandle (id) {
        let ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/tra/record/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      typeFormatter (row) {
        if (row.superiorType === true) {
          return '本单位职员'
        } else {
          return '机关单位'
        }
      },
      exportVisible () {
        this.exportVis = true
        this.getRewardList()
      },
      fileDownload (data, fileName) {
        console.log(data, fileName)
        let blob = new Blob([data], {
          type: 'application/octet-stream'
        })
        let filename = fileName
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // 解决IE不能导出
          window.navigator.msSaveBlob(blob, this.queryForm.date2 + filename + '.xlsx')
        } else {
          const blobUrl = window.URL.createObjectURL(new Blob([blob]))
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = blobUrl
          link.setAttribute('download', filename + '.xlsx')
          if (typeof link.download === 'undefined') {
            link.setAttribute('target', '_blank')
          }
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(blobUrl)
        }
      },
      // 导出提交
      exportSubmit () {
        this.$refs['exportForm'].validate((valid) => {
          if (valid) {
            this.isLoading = true
            this.$http({
              url: this.$http.adornUrl(`/tra/record/exportExcel`),
              method: 'post',
              responseType: 'blob',
              data: this.$http.adornData({
                'unitRwd': this.exportForm.unit,
                'staffRwd': this.exportForm.staff,
                'frontDeskRwd': this.exportForm.frontDesk,
                'resRwd': this.exportForm.res,
                'unitPeriod': this.exportForm.unitPeriod,
                'staffPeriod': this.exportForm.staffPeriod,
                'frontPeriod': this.exportForm.frontPeriod,
                'resPeriod': this.exportForm.resPeriod
              })
            }).then(function (res) {
              let filename = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1])
              this.fileDownload(res.data, filename)
              this.exportVis = false
              this.isLoading = false
              this.$notify({
                title: '成功',
                message: '导出成功！',
                type: 'success'
              })
            }.bind(this)).catch((error) => {
              this.exportVis = false
              this.isLoading = false
              this.$notify.error({
                title: '失败',
                message: error + '导出失败！'
              })
            })
          }
        })
      },
      getRewardList () {
        this.rewardVisible = true
        this.$nextTick(() => {
          this.$refs['exportForm'].resetFields()
          this.$http({
            url: this.$http.adornUrl('/tra/record/rewardInfo'),
            method: 'get'
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.exportForm.unit = data.list.unitRwd
              this.exportForm.staff = data.list.staffRwd
              this.exportForm.frontDesk = data.list.frontDeskRwd
              this.exportForm.res = data.list.resRwd
            } else {
              this.dataList = []
              this.totalPage = 0
            }
            this.dataListLoading = false
          })
        })
      }
    }
  }
</script>
